from starlette.responses import JSONResponse

from config.exceptions import ExistError
from models.permission import Permission
from repositories.permission_repositories import PermissionRepository
from schemas.users import PermissionCreate, PermissionResponse, PermissionUpdate, PermissionsResponse


# 将Permission对象转换为PermissionResponse对象
def set_permission_response(permission: Permission) -> PermissionResponse | None:
    if permission:
        return PermissionResponse.model_validate(permission.model_dump())
    else:
        return None

class PermissionService:
    def __init__(self, permission_repo: PermissionRepository):
        self.permission_repo = permission_repo


    def validate_permission_exists(self, permission_data: PermissionCreate | PermissionUpdate) -> bool:
        permission = self.permission_repo.get_permission_by_name(permission_data.name)
        if permission:
            raise ExistError(detail="权限已存在")
        elif permission_data.father_id:
            father_permission = self.permission_repo.get_permission_obj_by_id(permission_data.father_id)
            if not father_permission:
                raise ExistError(detail="父权限不存在")
        else:
            return False

    def create_permission(self, permission_data: PermissionCreate) -> PermissionResponse:
        if not self.validate_permission_exists(permission_data):
            permission_data = Permission.model_validate(permission_data)
            return self.permission_repo.create_or_update_permission(permission_data)

    def update_permission(self, permission_data: PermissionUpdate) -> PermissionResponse:
        permission = self.permission_repo.get_permission_obj_by_id(permission_data.id)
        if not permission:
            raise ExistError(detail="权限不存在")
        permission.sqlmodel_update(permission_data)
        return self.permission_repo.create_or_update_permission(permission)


    def filter_permissions(self, page:int|None, size:int|None) -> PermissionsResponse:
        return PermissionsResponse(data=[set_permission_response(permission) for permission in self.permission_repo.filter_permissions(page, size)],
                                   paging={"page": page, "size": size, "total": self.permission_repo.get_permissions_count()})


    def delete_permission(self, permission_id:int):
        permission = self.permission_repo.get_permission_obj_by_id(permission_id)
        if not permission:
            raise ExistError(detail="权限不存在")
        if permission.roles:
            raise ExistError(detail="该权限已被角色关联，无法删除")
        if self.permission_repo.get_permissions_by_father_id(permission_id):
            raise ExistError(detail="该权限有子权限，无法删除")
        self.permission_repo.delete_permission(permission_id)
        return JSONResponse(content={"message": "success"}, status_code=200)
